package push

import (
	"encoding/json"
	"errors"
	"fmt"
	"parking-lot-go-dingding/controller"
)

// 发送模板消息
func sendTemplateMsg(corpId string, templateId string, dingUserId string, data map[string]interface{}) (string, error) {
	agentId, err := controller.GetAgentId(corpId)
	if err != nil {
		return "", errors.New(fmt.Sprintf("获取agentId失败,:%s", err.Error()))
	}

	accessToken, err := controller.AccessToken(corpId)
	if err != nil {
		return "", errors.New(fmt.Sprintf("获取access_token失败:%s", err.Error()))
	}

	dataJson, err := json.Marshal(data)
	if err != nil {
		return "", errors.New(fmt.Sprintf("转换json失败:%s", err.Error()))
	}

	param := map[string]interface{}{
		"agent_id":     agentId,
		"template_id":  templateId,
		"userid_list":  dingUserId,
		"data":         string(dataJson),
		"access_token": accessToken,
	}

	url := "https://oapi.dingtalk.com/topapi/message/corpconversation/sendbytemplate?access_token=" + accessToken
	response, err := controller.PostJsonRequest(url, param)
	if err != nil {
		return "", errors.New(fmt.Sprintf("发送模板消息失败:%s", err.Error()))
	}
	return string(response), nil
}
